'use client'

import { useUserStore } from '@/store/user'
import request from '@/utils/frontend/request'
import { LockOutlined, SafetyOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Form, Input, message } from 'antd'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { setToken } from '@/utils/frontend/token'

interface LoginForm {
	username: string
	password: string
	code: string
}

export default function LoginPage() {
	const router = useRouter()
	const [form] = Form.useForm()
	const [captcha, setCaptcha] = useState('')
	const [loading, setLoading] = useState(false)
	const { setUserInfo } = useUserStore()
	const [messageApi, contextHolder] = message.useMessage()

	const getCaptcha = async () => {
		try {
			const { data } = await request.get('/auth/code')
			setCaptcha(data)
		} catch (errorMsg) {
			messageApi.error(errorMsg as string)
		}
	}

	useEffect(() => {
		getCaptcha()
	}, [])

	const onFinish = async (values: LoginForm) => {
		try {
			setLoading(true)
			const { data, message } = (await request.post('/auth/login', values)) as ApiResponse
			setToken(data.token)
			setUserInfo(data.userInfo)
			messageApi.success(message)
			if (data.userInfo.role === 'admin') {
				router.push('/admin/user')
			} else {
				router.push('/im-system')
			}
		} catch (errorMsg) {
			messageApi.error(errorMsg as string)
		} finally {
			setLoading(false)
		}
	}

	return (
		<div className="min-h-screen flex items-center justify-center bg-gray-50">
			{contextHolder}
			<div className="max-w-md w-full space-y-8 p-8 bg-white rounded-lg shadow-lg">
				<div>
					<h2 className="text-center text-3xl font-extrabold text-gray-900">登录系统</h2>
					<p className="mt-2 text-center text-sm text-gray-600">IM实时通讯系统</p>
				</div>

				<Form form={form} name="login" onFinish={onFinish} className="mt-8 space-y-6" size="large">
					<Form.Item name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
						<Input prefix={<UserOutlined />} placeholder="用户名" className="rounded-md" />
					</Form.Item>

					<Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
						<Input.Password prefix={<LockOutlined />} placeholder="密码" className="rounded-md" />
					</Form.Item>

					<Form.Item name="code" rules={[{ required: true, message: '请输入验证码!' }]}>
						<div className="flex gap-4">
							<Input prefix={<SafetyOutlined />} placeholder="验证码" className="rounded-md" />
							<div
								className="cursor-pointer"
								onClick={getCaptcha}
								dangerouslySetInnerHTML={{ __html: captcha }}
							/>
						</div>
					</Form.Item>

					<Form.Item>
						<Button
							type="primary"
							htmlType="submit"
							loading={loading}
							className="w-full bg-blue-600 hover:bg-blue-700"
						>
							登录
						</Button>
					</Form.Item>
				</Form>
			</div>
		</div>
	)
}
